% convert continuous EEGLAB  
% files to epoch data files
% -------------------------
subjectNames = { 'c1'  'c2'  'c3'  'c4'  'c5'  'c6'  'c7'  'c8' ...
                 'nd1' 'nd2' 'nd3' 'nd4' 'nd5' 'nd6' 'nd7' 'nd8' };
highpassFilter = 0.5;
lowpassFilter  = 50;

for index = 1:length(subjectNames)
    filenameset = fullfile(subjectNames{index}, [ subjectNames{index} '_continuous.set' ]); 
    EEG = pop_loadset(filenameset);

    % filtrage a 0.2
    disp('Filtering data...');
    for cind = 1:EEG.nbchan
       EEG.data(cind,:) = detrend(EEG.data(cind,:));
    end;
    EEG = pop_iirfilt( EEG, highpassFilter, 0, [], [0]);
    EEG = pop_iirfilt( EEG,  0, lowpassFilter, [], [0]);

    % extract all events
    % ------------------
    EEG2 = pop_selectevent( EEG, 'type', {  'audio'  'blank'  'both'  'light'  }, 'deleteevents', 'on');
    allIndices = [ EEG.event.indexinsession ];
    ind1  = find(allIndices == 1);
    ind50 = find(allIndices == 50);
    latencyRange = [ EEG2.event(ind50(2)).latency+20*EEG.srate EEG2.event(ind1(3)).latency-20*EEG.srate ];
    
    EEG2 = pop_select(EEG, 'point', latencyRange);
    if length(EEG2.event) > 2
        error('More than 1 event');
    end;
    if EEG2.pnts < EEG.srate*40
        ('Short segment');
    end;
    EEG2.event = [];
    EEG2 = eeg_regepochs(EEG2, 1, [0 1]);
    EEG2 = pop_autorej(EEG2, 'nogui', 'on');
    
    filenameset = fullfile(subjectNames{index}, [ subjectNames{index} '_med.set' ]);
    EEG2.group     = fastif(subjectNames{index}(1) == 'c', 'control', 'nondual');
    EEG2.subject   = subjectNames{index};
    EEG2 = pop_saveset(EEG2, filenameset);
end;
